import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import LocalCache from '../ultills/cache'
import { mapMenusToRoutes } from '../ultills/map-mennus'
// import { firstMenu } from '../ultills/map-mennus'
// import { mapMenusToRoutes } from '../ultills/map-mennus'
// import store from '../store/index'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    component: () => import('../views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('../views/main/main.vue'),
    children: [
      {
        path: '/userinfo',
        component: () => import('../views/userinfo/userinfo.vue')
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: '/not-found',
    component: () => import('../views/not-found/not-found.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
let isReafresh = true
// 导航守卫，看是否登录，决定是否跳转到登录页还是首页
router.beforeEach((to, from, next) => {
  if (localStorage.getItem('UserMenus')) {
    const routes = mapMenusToRoutes(
      JSON.parse(localStorage.getItem('UserMenus'))
    ) as any
    if (isReafresh) {
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      next({ ...to, replace: true })
      isReafresh = false
    } else {
      if (localStorage.getItem('token')) {
        console.log(routes)
        next()
      } else {
        return '/login'
      }
    }
  }

  // console.log(store)
  // const { commit } = store
  // if (sessionStorage.getItem('token')) {
  //   commit('login/changeToken', sessionStorage.getItem('token'))
  //   console.log(store.state)
  //   sessionStorage.clear()
  //   if (to.path !== '/login') {
  //     const token = LocalCache.getCache('token')
  //     if (!token && sessionStorage.getItem('token')) {
  //       return '/login'
  //     }
  //     // const userMenus = (store.state as any).login.userMenus
  //     // const routes = mapMenusToRoutes(userMenus)

  //     // routes.forEach((route) => {
  //     //   router.addRoute('mian', route)
  //     // })
  //   }
  // }

  // if (to.path === '/main') {
  //   return firstMenu.url
  // }
})
export default router
